package com.mall.user.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 1530009312@qq.com
 * @date Created in 2021/6/18 22:00
 * @description
 */

@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    //Json 转换值，可以通过json作为一个媒介
    ObjectMapper objectMapper = new ObjectMapper();

    //输入映射 String[] → String
    //index:输入映射过程中，预编译 占位符的顺序
    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] integers, JdbcType jdbcType) throws SQLException {
        /*preparedStatement对底层Jdbc做了一个封装，index输入映射占位符顺序*/
        String value = objectMapper.writeValueAsString(integers);/*传入integers就获得一个字符串value*/
        preparedStatement.setString(index,value);
    }

    //输出映射 数据库 String → String[]  结果封装，这个就是由String转换为String数组
    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        /*columnName不是查询结果，而是一个列名，根据查询结果的列名resultSet获得查询结果*/
        String result = resultSet.getString(columnName);
        /*result才是一个查询结果*/
        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int index) throws SQLException {
        /*index查询结果的句号，根据句号获得结果及*/
        String result = resultSet.getString(index);
        return transfer(result);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int index) throws SQLException {
        String result = callableStatement.getString(index);
        return transfer(result);
    }

    /*相当于抛出异常*/
    @SneakyThrows
    private String[] transfer(String result) {
        /*字符串转换为String数组*/
        if (result == null || "".equals(result)) {
            return new String[0];
        }
        String[] strings = objectMapper.readValue(result, String[].class);
        return strings;
    }

}